package com.blog.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.common.core.constant.ServiceConst;
import com.blog.common.core.domain.R;
import com.blog.common.core.utils.AddressUtils;
import com.blog.common.core.utils.ip.IpUtils;
import com.blog.common.domain.dto.MessageDto;
import com.blog.common.domain.entity.Message;
import com.blog.common.domain.entity.SiteConfig;
import com.blog.common.domain.vo.MessageVo;
import com.blog.message.api.MQproduct.CommentProduct;
import com.blog.system.api.feign.RemoteConfigService;
import com.blog.common.mapper.dao.MessageMapper;
import com.blog.web.service.MessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 留言 服务实现类
 * </p>
 *
 * @author Valerie
 * @since 2023-02-18
 */
@Service
@RequiredArgsConstructor
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {


    private final MessageMapper messageMapper;


    private final RemoteConfigService remoteConfigService;


    private final HttpServletRequest request;

    private final CommentProduct commentProduct;

    @Override
    public List<MessageVo> listMessages() {
        List<Message> messageList = new LambdaQueryChainWrapper<>(messageMapper)
                .select(Message::getId, Message::getAvatar, Message::getNickname, Message::getTime, Message::getMessageContent)
                .eq(Message::getIsReview, ServiceConst.IS_TRUE)
                .eq(Message::getIsDelete, ServiceConst.IS_FALSE)
                .list();
        return BeanUtil.copyToList(messageList, MessageVo.class);
    }

    @Override
    public void saveMessage(MessageDto messageDto) {
        R<SiteConfig> r = remoteConfigService.getWebsiteConfig();
        String ipAddress = IpUtils.getIpAddr(request);
        String realAddressByIp = AddressUtils.getRealAddressByIp(ipAddress);
        Message message = BeanUtil.copyProperties(messageDto, Message.class);
        message.setIpAddress(ipAddress);
        message.setIpSource(realAddressByIp);
        messageMapper.insert(message);
        commentProduct.review(message);
    }
}
